package mce.cuce;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class IndexServlet
 */
@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IndexServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter pw = response.getWriter();
		pw.println("Index Page");
		
		String shorty = getShorty(request.getRequestURL().toString());
		
		if(shorty != null && shorty.length() > 0) {	//redirect
			String longUrl = DbService.getLongUrl(shorty);
			if(longUrl != null) {	//valid id, redirect
				response.sendRedirect(longUrl);
			} else {	//invalid id, error
				request.setAttribute("hataMesaji", "Invalid Url");
				RequestDispatcher disp = request.getRequestDispatcher("error.jsp");
				disp.forward(request, response);
			}
		} else {	//show form
			RequestDispatcher dispatcher = request.getRequestDispatcher("form.jsp");
			dispatcher.forward(request, response);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	/**
	 * 
	 * @param longUrl
	 * @return
	 */
	private String getShorty(String longUrl) {
		if(longUrl != null) {
			String param = longUrl.substring(longUrl.lastIndexOf("/") + 1);
			return param;
		}
		return null;
	}

}
